<?php

namespace lxs\wechat;

use Illuminate\Support\Facades\Log;
use lxs\aliyun\OssStorage;
use lxs\tools\Tools;
use OSS\Http\RequestCore_Exception;

class WeChatApplet extends OpenInterface
{

    /**
     * 生成小程序码
     * @param string $path 小程序页面路径
     * @param string $scene 小程序页面参数
     * @param int $width 二维码宽度
     * @param string $appid 小程序appid
     * @param string $secret 小程序secret
     */
    public function getMiniCode(string $path, string $scene, int $width = 150, string $appid='', string $secret=''): ?string
    {

        $accessToken = $this->getAccessToken($appid, $secret);
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$accessToken";
        $params = [
            'path' => $path,
            'width' => $width,
            'scene' => $scene
        ];
        $post_data = json_encode($params);
        $data = Tools::httpRequest($url, $post_data, 'POST');
        try {
            $res = (new OssStorage())->base64ToOss($data, 'qrcode');
            if ($res['code'] == 200) {
                return $res['oss_url'];
            }
            return false;
        } catch (RequestCore_Exception $e) {
            Log::error(date('Y-m-d H:i:s') . '小程序码生成失败' . PHP_EOL . $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL . $e->getFile() . ':' . $e->getLine());
            return false;
        }
    }


}
